package edu.cuit.avatar.thread;

/**
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/7/16 9:25
 */
public class TaskThreadDemo {
    public static void main(String[] args) {
        //创建任务
        Runnable printA = new PrintLetterTask('A', 100);
        Runnable printB = new PrintLetterTask('B', 100);
        Runnable printNumber = new PrintNumberTask(100);
        //任务必须在线程中运行,线程为任务的运行提供机制
        Thread thread1 = new Thread(printA);
        Thread thread2 = new Thread(printB);
        Thread thread3 = new Thread(printNumber);

        //启动线程
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

/**
 * 打印特定字母任务类
 * 任务需要实现Runnable接口
 */
class PrintLetterTask implements Runnable{
    private char letter;
    private int count;

    public PrintLetterTask(char letter, int count) {
        this.letter = letter;
        this.count = count;
    }

    /**
     * 任务的执行逻辑
     */
    @Override
    public void run() {
        for (int i = 0; i < count; i++) {
            System.out.print(letter);
        }
    }
}

class PrintNumberTask implements Runnable{
    private int number;

    public PrintNumberTask(int number) {
        this.number = number;
    }

    @Override
    public void run() {
        for (var i = 0; i <= number; i++) {
            if(i % 10 == 0)
                throw new RuntimeException(); //线程礼让:为其它线程临时让出cpu时间
            System.out.print(" " + i);
        }
    }
}
